<?php

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;


class GroupChatController extends AbstractActionController
{
    protected $storage;
    protected $authService;
    
    public function getAuthService()
    {
        if(!$this->authService)
        {
            $this->authService = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authService;
    }
    
    public function getLogedInUser()
    {
        $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
        $user = $userTable->getUserByEmail($this->getAuthService()->getStorage()->read());
        return $user;
    }
    
    public function indexAction()
    {
        $form = $this->getServiceLocator()->get('GroupChatForm');
        $user = $this->getLogedInUser();
        
        $request = $this->getRequest();
        if($request->isPost())
        {
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $messageTest = $request->getPost()->get('message');
                $fromUserId = $user->id;
                $this->sendMessage($messageTest, $fromUserId);
                // to prevent duplicate entries on refresh
                return $this->redirect()->toRoute('users/group-chat' , array('controller' => 'group-chat' , 'action' => 'index'));
                var_dump($form->getData());
            }
        }
        return new ViewModel(array(
            'form' => $form,
            'userName' => $user->name
        ));
    }
    
    
    public function sendMessage($message , $user_id)
    {
        //$groupChatTable = $this->getServiceLocator()->get('Users\Model\GroupChatTable');
        $chatMessageTG = $this->getServiceLocator()->get('ChatMessagesTableGateway');
        $data = array(
            'user_id' => $user_id ,
            'message' => $message ,
            'stamp' => NULL
        );
        $chatMessageTG->insert($data);
		
        return true;
    }
    
    public function messageListAction()
    {
        $groupChatTable = $this->getServiceLocator()->get('Users\Model\GroupChatTable');
        $messageList = $groupChatTable->fetchAll();
        
        return new ViewModel(array(
            'messageList' => $messageList
        ));
    }
}

